<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="激活状态" prop="active">
              <el-select v-model="queryParams.active" placeholder="请选择激活状态" clearable>
                <el-option v-for="dict in hardware_equip_active" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="激活时间" prop="activeTime">
              <el-date-picker v-model="queryParams.activeTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择激活时间" />
            </el-form-item>
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="queryParams.manufacturer" placeholder="请输入制造商" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="型号" prop="model">
              <el-input v-model="queryParams.model" placeholder="请输入型号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="运行状态" prop="runStatus">
              <el-select v-model="queryParams.runStatus" placeholder="请选择运行状态" clearable>
                <el-option v-for="dict in hardware_equip_run_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="上次运行" prop="lastStartTime">
              <el-date-picker v-model="queryParams.lastStartTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择上次运行" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['hardware:equip:add']" type="primary" plain icon="Plus" @click="handleAdd">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['hardware:equip:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['hardware:equip:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['hardware:equip:export']" type="warning" plain icon="Download" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="equipList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备编号" align="center" prop="id" />
        <el-table-column label="设备名" align="center" prop="name" />
        <el-table-column label="所属用户" align="center" prop="userName" />
        <!--        <el-table-column label="设备别名" align="center" prop="alias" />-->
        <el-table-column label="激活状态" align="center" prop="active">
          <template #default="scope">
            <dict-tag :options="hardware_equip_active" :value="scope.row.active" />
          </template>
        </el-table-column>
        <el-table-column label="激活时间" align="center" prop="activeTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.activeTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="制造商" align="center" prop="manufacturer" />
        <el-table-column label="型号" align="center" prop="model" />
        <!--        <el-table-column label="硬件版本" align="center" prop="firmwareVersion" />-->
        <!--        <el-table-column label="软件版本" align="center" prop="softwareVersion" />-->
        <!--        <el-table-column label="位置" align="center" prop="location" />-->
        <el-table-column label="运行状态" align="center" prop="runStatus">
          <template #default="scope">
            <div>
              <el-switch
                v-model="scope.row.runStatus"
                inline-prompt
                active-value="1"
                active-text="启"
                inactive-value="0"
                inactive-text="停"
                :disabled="!scope.row.active"
                @click="handleRunStatusChange(scope.row)"
              />
            </div>
          </template>
        </el-table-column>
        <!--        <el-table-column label="运行时间" align="center" prop="startTime" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="停止时间" align="center" prop="endTime" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="上次运行" align="center" prop="lastStartTime" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.lastStartTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="上次停止" align="center" prop="lastEndTime" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.lastEndTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['hardware:equip:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['hardware:equip:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>

            <el-tooltip v-if="scope.row.active === 0" content="激活" placement="top">
              <el-button v-hasPermi="['hardware:equip:unlock']" link type="primary" icon="Unlock" @click="activeForm(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设备对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="equipFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名" />
        </el-form-item>
        <el-form-item label="激活状态" prop="active">
          <el-radio-group v-model="form.active">
            <el-radio v-for="dict in hardware_equip_active" :key="dict.value" :value="parseInt(dict.value)">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="制造商" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入制造商" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="传感器" prop="sensors">
          <el-tree-select
            ref="sensorRef"
            v-model="form.sensorIds"
            class="tree-border"
            node-key="id"
            :data="sensorOptions"
            empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"
            multiple
            :render-after-expand="false"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="activeDialog.visible" :title="activeDialog.title" width="500px" append-to-body>
      <el-form ref="sysUserFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="绑定用户" prop="userId">
          <el-select v-model="form.userId" filterable placeholder="请选择绑定用户" style="width: 240px">
            <el-option
              v-for="item in sysUserList"
              :key="item.userId"
              :label="item.userName + ` - ` + item.phonenumber"
              :value="item.userName + ` - ` + item.phonenumber"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="handleActive">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Equip" lang="ts">
import { activeEquip, addEquip, changeEquipRunStatus, delEquip, getEquip, listEquip, updateEquip } from '@/api/hardware/equip';
import { EquipForm, EquipQuery, EquipVO } from '@/api/hardware/equip/types';
import { sensorsTreeselect } from '@/api/hardware/sensor';
import { selectUserList } from '@/api/system/user';
import { SensorTreeOption } from '@/api/hardware/sensor/types';
import { UserForm, UserVO } from '@/api/system/user/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { hardware_equip_active, hardware_equip_run_status } = toRefs<any>(proxy?.useDict('hardware_equip_active', 'hardware_equip_run_status'));

const equipList = ref<EquipVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const equipFormRef = ref<ElFormInstance>();
const sysUserFormRef = ref<ElFormInstance>();

const sensorRef = ref<ElTreeInstance>();
const sensorOptions = ref<SensorTreeOption[]>([]);
let sysUserList = ref<UserVO[]>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const activeDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: EquipForm = {
  id: undefined,
  name: undefined,
  userId: undefined,
  userName: undefined,
  alias: undefined,
  active: undefined,
  activeTime: undefined,
  manufacturer: undefined,
  model: undefined,
  firmwareVersion: undefined,
  softwareVersion: undefined,
  location: undefined,
  runStatus: undefined,
  startTime: undefined,
  endTime: undefined,
  lastStartTime: undefined,
  lastEndTime: undefined,
  sensorIds: undefined
};

const sysUserFormData: UserForm = {
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: undefined,
  password: '',
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  status: '0',
  remark: '',
  postIds: [],
  roleIds: []
};

const data = reactive<PageData<EquipForm, EquipQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    active: undefined,
    activeTime: undefined,
    manufacturer: undefined,
    model: undefined,
    firmwareVersion: undefined,
    softwareVersion: undefined,
    runStatus: undefined,
    lastStartTime: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '设备名不能为空', trigger: 'blur' }],
    manufacturer: [{ required: true, message: '制造商不能为空', trigger: 'blur' }],
    model: [{ required: true, message: '型号不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '请选择绑定用户', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备列表 */
const getList = async () => {
  loading.value = true;
  const res = await listEquip(queryParams.value);
  equipList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  activeDialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  equipFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: EquipVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getSensorsTreeselect();
  dialog.visible = true;
  dialog.title = '添加设备';
};

/** 查询传感器树结构 */
const getSensorsTreeselect = async () => {
  const res = await sensorsTreeselect();
  sensorOptions.value = res.data;
};

const handleRunStatusChange = async (row: EquipVO) => {
  let tmpStatus = row.runStatus + '';
  let text = tmpStatus === '0' ? '停用' : '启用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '"吗?');
    await changeEquipRunStatus(row.id, row.runStatus);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    row.runStatus = tmpStatus === '0' ? 1 : 0;
  }
};

/** 修改按钮操作 */
const handleUpdate = async (row?: EquipVO) => {
  reset();
  await getSensorsTreeselect();
  const _id = row?.id || ids.value[0];
  const res = await getEquip(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改设备';
};

/** 提交按钮 */
const submitForm = () => {
  equipFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateEquip(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addEquip(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: EquipVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delEquip(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 激活按钮操作 */
const handleActive = () => {
  sysUserFormRef.value?.validate(async (v: boolean) => {
    if (v) {
      console.log(form);
      const id = form.value.id;
      await activeEquip(id);
      proxy?.$modal.msgSuccess('激活成功');
      cancel();
      await getList();
    }
  });
};

const activeForm = async (row?: EquipVO) => {
  Object.assign(form.value, row);
  sysUserList.value = await selectUserList();
  activeDialog.visible = true;
  activeDialog.title = '激活设备 : ' + row.id;
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'hardware/equip/export',
    {
      ...queryParams.value
    },
    `equip_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
